package LL6;

public class Main {

    // Definition for singly-linked list.
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    static class Solution {
        public ListNode middleNode(ListNode head) {
            //1.定义快慢指针
            ListNode fast = head; //快指针
            ListNode slow = head; //慢指针

            //2.移动快慢指针
            while (fast != null && fast.next != null) {
                fast = fast.next.next; //每次移动 2 个节点
                slow = slow.next; //每次移动 1 个节点
            }
            return slow;
        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = new ListNode(6);

        Solution solution = new Solution();
        ListNode node = solution.middleNode(head);
        System.out.println(node.val);
    }
}
